package com.zhl.gradledemo.util;

import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;

/**
 * 常规的响应内容，只允许在controller中应用包装用
 * @author austinChen
 * Created by austinChen on 2019/4/23 11:54.
 */
@Getter
@Setter
public class HttpResult {

    private static final  String SUCCESS_MSG="成功";
    private static final  String FAIL_MSG="失败";

    @ApiModelProperty(value = "响应代码200为成功,500为服务器异常", required = true)
    private int code ;
    @ApiModelProperty(value = "返回信息", required = false)
    private String msg;
    @ApiModelProperty(value = "响应数据对象,分页参见PageInfoMock对象，多对象返回使用map", required = true)
    private Object data;

    /**
     * @param code 根据code内容进行code定义
     * @return
     */
    public  HttpResult setCode(int code) {
        this.code=code;
        return this;
    }

    /**
     * @param data 根据data内容进行data定义
     * @return
     */
    public  HttpResult setData(Object  data) {
        this.data=data;
        return this;
    }

    /**
     * @param msg 根据msg内容进行msg定义
     * @return
     */
    public  HttpResult setMsg(String msg) {
        this.msg=msg;
        return this;
    }


    /**
     * @param code 返回code
     * @param msg 消息内容
     * @return
     */
    public static HttpResult ret(int code,String msg) {
        return ret(code,msg,null);
    }


    /**
     * @param code 返回code
     * @param msg 消息内容
     * @param data 数据内容
     * @return
     */
    public static HttpResult ret(int code,String msg,Object data) {
        HttpResult r = new HttpResult();
        r.setCode(code);
        r.setMsg(msg);
        r.setData(data);
        return r;
    }

    /**
     * @return 默认的成功返回
     */
    public static HttpResult suc() {
       return suc(SUCCESS_MSG);
    }

    /**
     * @param data 成功返回的data数据
     * @return
     */
    public static HttpResult suc(Object data) {
        HttpResult r = suc();
        r.setData(data);
        return r;
    }

    /**
     * @param msg 默认返回的消息内容
     * @return 成功的消息内容
     */
    public static HttpResult suc(String msg) {
        HttpResult r = new HttpResult();
        r.setCode(HttpStatus.OK.value());
        r.setMsg(msg);
        return r;
    }


    /**
     * @return 默认的失败消息
     */
    public static HttpResult fail() {
        return fail(FAIL_MSG);
    }

    /**
     * @param throwable 根据异常的message返回
     * @return
     */
    public static HttpResult fail(Throwable throwable) {
       return fail(throwable.getMessage());
    }

    /**
     * @param msg 根据msg内容进行异常返回
     * @return
     */
    public static HttpResult fail(String msg) {
        HttpResult r = new HttpResult();
        r.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        r.setMsg(msg);
        return r;
    }
}
